<?php
namespace common\modules\user\frontend\models;

use common\modules\user\models\User;
use Yii;
use yii\base\InvalidParamException;
use yii\base\Model;

/**
 * Password reset form
 */
class ResetPasswordForm extends Model
{

    public $password;

    /**
     *
     * @var \common\models\User
     */
    private $user;

    /**
     * Creates a form model given a token.
     *
     * @param string $token            
     * @param array $config
     *            name-value pairs that will be used to initialize the object properties
     * @throws \yii\base\InvalidParamException if token is empty or not valid
     */
    public function __construct($token, $config = [])
    {
        if (empty($token) || ! is_string($token)) {
            throw new InvalidParamException('Password reset token cannot be blank.');
        }
        $this->user = User::findByPasswordResetToken($token);
        if (! $this->user) {
            throw new InvalidParamException('Wrong password reset token.');
        }
        parent::__construct($config);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [
                'password',
                'required'
            ],
            [
                'password',
                'string',
                'min' => 6
            ]
        ];
    }

    /**
     * Resets password.
     *
     * @return boolean if password was reset.
     */
    public function resetPassword()
    {
        $user = $this->user;
        $user->password = $this->password;
        $user->removePasswordResetToken();
        
        return $user->save();
    }

    public function attributeLabels()
    {
        return [
            'password' => Yii::t('frontend', 'Password')
        ];
    }
}
